package com.xmc.utils;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 将响应数据写回
 *
 * @author wyj
 * @create 2019-04-29 21:27
 */
public class ResultWriter {

    /**
     * 默认的HTTP错误码
     */
    private static int defaultErrorStatusCode = 404;

    /**
     * 默认的响应数据的内容类型
     */
    private static String defaultContentType = "application/json";

    /**
     * 写回响应数据
     * @param response 响应对象，用于设置contentType和获取PrintWriter。
     * @param result 要写回的对象(在本方法内部用JSON.toJSONString()转换为jsonStr格式)
     * @param prettyFormat 是否美化json串的格式
     * @param contentType 响应的内容类型，默认为"text/json"
     * @throws IOException 可能由response.getWriter()抛出
     */
    public static void write(HttpServletResponse response, Object result, boolean prettyFormat, String contentType) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(result, prettyFormat));
        System.out.println(JSON.toJSONString(result,prettyFormat));
        writer.close();
    }
    public static void write(HttpServletResponse response, Object result) throws IOException {
        write(response, result, true, defaultContentType);
    }

    /**
     * 后端操作出错时，写回响应消息
     * @param response 响应
     * @param msg 要写回的消息
     * @param status 返回的HTTP错误码
     * @param contentType 响应的内容类型
     * @throws IOException
     */
    public static void occurException(HttpServletResponse response, Object msg, int status, String contentType) throws IOException {
        response.setStatus(status);
        response.setContentType(contentType);
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(msg));   // 写回错误数据
        System.out.println(JSON.toJSONString(msg));
        writer.close();
    }
    public static void occurException(HttpServletResponse response, Object msg) throws IOException {
        occurException(response, msg, defaultErrorStatusCode, defaultContentType);
    }

}

